var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var session = require("express-session");
var MongoDBStore = require("connect-mongodb-session")(session);

var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");
var accountRouter = require("./routes/account");

var app = express();

// 设置session
app.use(
  session({
    name: "sess", // 设置cookie的name，默认值是：connect.sid
    secret: "atguigu", // 参与加密的字符串（又称签名）
    saveUninitialized: false, //是否为每次请求都设置一个 cookie 用来存储 session 的 id
    resave: false, // 强制保存 session 即使它并没有变化, 默认为 true,建议设置成 false。
    cookie: {
      httpOnly: true, // 开启后前端无法通过 JS 操作
      maxAge: 1000 * 30, // 这一条 是控制 sessionID 的过期时间的！！！
    },
    // 存放再mongodb中
    store: new MongoDBStore({
      uri: "mongodb://127.0.0.1:27017/account-project",
      collection: "userSession",
    }),
  })
);

// view engine setup
// 指定模板引擎
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
// 静态路由托管
app.use(express.static(path.join(__dirname, "public")));

app.use("/", indexRouter);


app.use("/users", usersRouter);
app.use("/account", accountRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
